//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

//只有stream接口用rust实现

use futures_util::StreamExt;
use tauri::{
    http::{HeaderMap, HeaderValue},
    ipc::Channel,
};
use tauri_plugin_http::reqwest;

#[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq)]
pub struct ChatMsgChunkData {
    pub success: bool,
    pub value: String,
}

#[tauri::command]
pub async fn llm_cmds_chat_completion(
    addr: String,
    api_key: String,
    body: String,
    on_event: Channel<ChatMsgChunkData>,
) {
    let mut headers = HeaderMap::new();
    let content_type = HeaderValue::from_static("application/json");
    headers.append("Content-Type", content_type);
    let origin = HeaderValue::from_static("");
    headers.append("Origin", origin); //fix http with unsafe-header return 403
    if api_key != "" {
        let auth = format!("Bearer {}", &api_key);
        let auth = HeaderValue::from_str(&auth);
        if auth.is_err() {
            let _ = on_event.send(ChatMsgChunkData {
                success: false,
                value: auth.err().unwrap().to_string(),
            });
            return;
        }
        let auth = auth.unwrap();
        headers.append("Authorization", auth);
    }
    let client = reqwest::Client::new();
    let res = client.post(addr).body(body).headers(headers).send().await;
    if res.is_err() {
        let _ = on_event.send(ChatMsgChunkData {
            success: false,
            value: res.err().unwrap().to_string(),
        });
        return;
    }
    let res = res.unwrap();
    let mut stream = res.bytes_stream();
    while let Some(item) = stream.next().await {
        if item.is_err() {
            continue;
        }
        let item = item.unwrap().to_vec();
        let _ = on_event.send(ChatMsgChunkData {
            success: true,
            value: String::from_utf8_lossy(&item).to_string(),
        });
    }
}
